<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Config, UserAuth, UserSafety, ContractList, ContractOrder, ContractReser, ContractSell, HallApple, CoinsPrice, ContractApply};
use think\Facade\Config as Configs;
use think\Validate;
use think\Db;

class Conntract extends Base
{
    //注册账号
    public function lists()
    {
        $list = (new ContractList())->where('status', 1)->field('level,status,automatch', true)->select();
        foreach ($list as $lists) {
            $lists['status_type'] = 1;
            $lists['status_text'] = '预约';
            if (date('H:i') < $lists['start_time']) {
                $lists['status_type'] = 1;
                $lists['status_text'] = '预约';
            }
            if (date('H:i') >= $lists['end_time']) {
                $lists['status_type'] = 2;
                $lists['status_text'] = '已结束';
            }
            if (date('H:i') < $lists['end_time'] && date('H:i') >= $lists['start_time']) {
                $lists['status_type'] = 5;
                $lists['status_text'] = '抢购';
            }
            //是否存在抢购和预约
            $havereser = (new ContractReser())->where(['user_id' => $this->request->user_id, 'cate_id' => $lists['id'], 'status' => 1])->find();
            if (!empty($havereser) && $havereser['type'] == 2) {
                $lists['status_type'] = 3;
                $lists['status_text'] = '已预约';
            }
            if (!empty($havereser) && $havereser['type'] == 1) {
                $lists['status_type'] = 4;
                $lists['status_text'] = '抢购中';
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function info()
    {
        $lists = (new ContractOrder())->where(['user_id' => $this->request->user_id])->select();
        $income = 0;
        $todayincome = 0;
        foreach ($lists as $list) {
            $income += $list['allincome'];
            if ($list['incometime'] >= date('Y-m-d')) {
                $todayincome += round($list['figure'] * $list['product_price'] / 100, 2);
            }
        }
        $result['income'] = $income;
        $result['allincome'] = $todayincome;
        $this->result($result, 0, '获取成功');
    }

    public function adopt()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => 'ID不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $auth = (new UserAuth())->where('user_id', $this->request->user_id)->find();
            if (empty($auth) || $auth['status'] != 2) {
                $this->result([], 1, '请先进行身份认证');
            }
            $safety = (new UserSafety())->where(['user_id' => $this->request->user_id, 'type' => [1, 2, 3]])->count();
            if ($safety < 3) {
                $this->result([], 1, '请先绑定微信、支付宝和银行卡信息');
            }
            //查询Redis信息数据
            $contractlist = (new ContractList())->where(['id' => $data['id'], 'status' => 1])->find();
            if (empty($contractlist)) {
                $this->result([], 1, '合约信息不存在');
            }
            //判断抢购或预约类型
            $type = 1; //抢购
            $type_text = '抢购';
            $types = 4;
            $money = $contractlist->snappoints;
            if (date('H:i') >= $contractlist->end_time) {
                $this->result([], 1, '合约已结束，请提前预约、抢购');
            }
            if (date('H:i') < $contractlist->start_time) {
                $type = 2; //预约
                $type_text = '预约';
                $money = $contractlist->reserpoints;
                $types = 5;
            }
            $havereser = (new ContractReser())->where(['user_id' => $this->request->user_id, 'cate_id' => $contractlist->id, 'status' => 1])->find();
            if (!empty($havereser)) {
                $this->result([], 1, '您已预约|抢购,无需重复操作');
            }
            if ($this->request->user['money'] < $money) {
                $this->result([], 1, 'PDB数目不足');
            }
            Db::startTrans();
            try {
                $id = (new ContractReser())->insertGetId([
                    'user_id' => $this->request->user_id,
                    'name' => $contractlist->name,
                    'cate_id' => $contractlist->id,
                    'money' => $money,
                    'dates' => date('Y-m-d'),
                    'type' => $type,
                    'status' => 1
                ]);
                if ($money > 0) {
                    (new Users())->MoneyEdit($this->request->user_id, $this->request->user['money'], -$money, 1, $types, $type_text . '合约', $id);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $type_text . '失败，请重试');
            }
            $this->result([], 0,  $type_text . '成功,请等待匹配');
        }
    }

    public function reser()
    {
        $list = (new ContractReser())->order('id desc')->field('name,money,type,created,status')->where('user_id', $this->request->user_id)->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '获取成功');
    }

    public function Mycontract()
    {
        $type = $this->request->get('type/d', '');
        if ($type == 1) {
            $list = (new ContractOrder())->order('id desc')->where([
                'user_id' => $this->request->user_id,
                'income_status' => 2,
                'status' => 3
            ])->field('id,product_id,product_name,price,days,figure,created,idays,product_price')->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($list as $lists) {
                $lists['ordersn'] = pow(12, 10) + $lists['id'];
                $lists['idays'] = $lists['days'] - $lists['idays'];
            }
        } elseif ($type == 2) {
            $list = (new ContractSell())->order('id desc')->where([
                'user_id' => $this->request->user_id, 'status' => 1
            ])->field('id,product_id,product_name,price,created,status,orderid')->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($list as $lists) {
                $contract = (new ContractList())->where('id', $lists['product_id'])->find();
                $lists['ordersn'] = pow(12, 10) + $lists['orderid'];
                $lists['days'] =  $contract['cycle'] ?? 0;
                $lists['figure'] =  $contract['income'] ?? 0;
                $lists['product_price'] =  $lists['buyprice'] ?? 0;
                unset($lists['orderid']);
            }
        } else {
            $list = (new ContractOrder())->order('id desc')->where([
                'seller_id' => $this->request->user_id,
                'status' => 3,
                'income_status' => 3,
            ])->field('id,product_id,product_name,price,days,figure,created,product_price')->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($list as $lists) {
                $lists['ordersn'] = pow(12, 10) + $lists['id'];
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function Mycontracting()
    {
        $type = $this->request->get('type/d', '');
        $status = $this->request->get('status/d', '');
        $list = (new ContractOrder())->order('id desc');
        if ($type == 1) {
            $list = $list->where(['seller_id' => $this->request->user_id]);
        } elseif ($type == 2) {
            $list = $list->where(['user_id' => $this->request->user_id]);
        } else {
            $list = $list->where(['user_id|seller_id' => $this->request->user_id]);
        }
        if (!empty($status)) {
            if ($status == 5) {
                $list = $list->where(['status' => [5, 6]]);
            } elseif ($status == 4) {
                $list = $list->where(['status' => [3, 4]]);
            } else {
                $list = $list->where(['status' => $status]);
            }
        } else {
            $list = $list->where(['status' => [1, 2, 5, 6]]);
        }
        $list = $list->field('id,product_id,user_id,seller_id,product_name,price,days,figure,created,status')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['ordersn'] = pow(12, 10) + $lists['id'];
            $lists['status_text'] = $lists->statusname;
            if ($lists['user_id'] == $this->request->user_id) {
                $lists['sellbuy_type'] = 1;
            }
            if ($lists['seller_id'] == $this->request->user_id) {
                $lists['sellbuy_type'] = 2;
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function Cacelcontracting()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'trade' => 'require',
            ], [
                'id.require' => 'Id不能为空',
                'id.gt' => 'Id必须大于0',
                'trade.require' => '交易密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $this->result([], 1, '取消通道已关闭');
            $user = $this->request->user;
            if (md5(md5($data['trade'])) != $user['trade']) {
                $this->result([], 1, '交易密码错误');
            }
            $order = (new ContractOrder())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            if ($order['user_id'] != $this->request->user_id) {
                $this->result([], 1, '非买家用户无法操作');
            }
            if ($order['status'] != 1 && $order['status'] != 2) {
                $this->result([], 1, '订单状态不可取消');
            }
            Db::startTrans();
            try {
                (new ContractOrder())->where(['id' => $data['id']])->update(['status' => 4, 'incometime' => date('Y-m-d H:i:s')]);
                (new ContractSell())->where('id', $order['matchid'])->update(['status' => 1]);
                Db::commit();
            } catch (\Exception $e) {
                dump($e->getMessage());
                Db::rollback();
                $this->result([], 1, '取消失败，请重试');
            }
            $this->result([], 0, '取消成功');
        }
    }

    //订单付款
    public function Paycontract()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'payimages' => 'require',
                'trade_type' => 'require|in:1,2,3',
                'trade' => 'require'
            ], [
                'id.require' => 'Id不能为空',
                'id.gt' => 'Id必须大于0',
                'payimages.require' => '付款凭证不能为空',
                'trade_type.require' => '付款类型不能为空',
                'trade_type.in' => '付款类型不正确',
                'trade.require' => '交易密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if (md5(md5($data['trade'])) != $user['trade']) {
                $this->result([], 1, '交易密码错误');
            }
            $order = (new ContractOrder())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            if ($order['status'] != 1) {
                $this->result([], 1, '订单状态不可付款');
            }
            if ($order['user_id'] != $this->request->user_id) {
                $this->result([], 1, '非买家用户，无法操作');
            }
            Db::startTrans();
            try {
                (new ContractOrder())->where(['id' => $data['id']])->update([
                    'status' => 2,
                    'images' => $data['payimages'],
                    'trade_type' => $data['trade_type'],
                    'paytime' => date('Y-m-d H:i:s')
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        }
    }

    //订单确认
    public function Endcontract()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'trade' => 'require'
            ], [
                'id.require' => 'Id不能为空',
                'id.gt' => 'Id必须大于0',
                'trade.require' => '交易密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if (md5(md5($data['trade'])) != $user['trade']) {
                $this->result([], 1, '交易密码错误');
            }
            $order = (new ContractOrder())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            if ($order['status'] != 2) {
                $this->result([], 1, '订单状态不可确认');
            }
            if ($order['seller_id'] != $this->request->user_id) {
                $this->result([], 1, '非卖家用户，无法操作');
            }
            $sell = (new ContractSell())->where('id', $order['matchid'])->find();
            //卖家收益计算
            $money = $sell['price'] - $sell['buyprice'];
            Db::startTrans();
            try {
                (new ContractOrder())->where(['id' => $data['id']])->update(['status' => 3, 'income_status' => 2, 'incometime' => date('Y-m-d H:i:s'), 'finishtime' => date('Y-m-d H:i:s')]);
                (new ContractSell())->where('id', $order['matchid'])->update(['status' => 3]);
                if ($money > 0) {
                    (new Users())->where('id', $sell['user_id'])->setInc('cincome', $money);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        }
    }

    //申诉订单
    public function Applycontract()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'info' => 'require',
            ], [
                'id.require' => 'Id不能为空',
                'id.gt' => 'Id必须大于0',
                'info.require' => '投诉理由不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['images'])) {
                $images = json_decode($data['images'], true);
                if (empty($images)) {
                    $this->result([], 1, '图片上传格式错误');
                }
            }
            $user = $this->request->user;
            $order = (new ContractOrder())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            if ($order['status'] != 1 && $order['status'] != 2) {
                $this->result([], 1, '订单状态不可申诉');
            }
            if ($order['status'] == 1 && $order['user_id'] == $user['id']) {
                $this->result([], 1, '未付款状态买家请选择取消');
            }
            if ($order['seller_id'] != $user['id'] && $order['user_id'] != $user['id']) {
                $this->result([], 1, '非交易玩家订单无法操作');
            }
            if ($order['user_id'] == $user['id']) {
                $status = 5;
            }
            if ($order['seller_id'] == $user['id']) {
                $status = 6;
            }
            Db::startTrans();
            try {
                (new ContractOrder())->where(['id' => $data['id']])->update(['status' => $status]);
                (new HallApple())->insert([
                    'user_id' => $user['id'],
                    'hallid' => $order['id'],
                    'info' => $data['info'],
                    'images' => $data['images'] ?? '',
                    'type' => 2,
                    'status' => 1
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '申诉失败，请重试');
            }
            $this->result([], 0, '申诉成功，请等待管理员审核');
        }
    }

    public function Detailcontract()
    {
        $id = $this->request->get('id/d', 0);
        $order = (new ContractOrder())->where('id', $id)->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        if ($order['user_id'] != $this->request->user_id && $order['seller_id'] != $this->request->user_id) {
            $this->result([], 1, '无权限');
        }
        if ($order['user_id'] == $this->request->user_id) {
            $order['mobile'] = (new Users())->where('id', $order['seller_id'])->value('mobile');
            $order['safety'] = (new UserSafety())->where('user_id', $order['seller_id'])->field('id,user_id,created,updated', true)->select();
            $order['ordertype'] = 2;
        }
        if ($order['seller_id'] == $this->request->user_id) {
            $order['mobile'] = (new Users())->where('id', $order['user_id'])->value('mobile');
            $order['ordertype'] = 1;
        }
        $order['status_text'] = $order->statusname;
        $order['ordersn'] = pow(12, 10) + $order['id'];
        $this->result($order, 0, '获取成功');
    }

    public function Exchange()
    {
        $id = $this->request->post('id/d', 0);
        $order = (new ContractSell())->where(['id' => $id, 'user_id' => $this->request->user_id])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        if ($order['status'] != 1) {
            $this->result([], 1, '订单不可兑换');
        }
        $orderlist = Redis::get('contractreser' . $order['id']); //存储库存
        if ($orderlist) {
            $this->result([], 1, '订单处于匹配阶段，请稍后再试');
        }
        //判断可兑换多少钱
        $price = (new CoinsPrice())->where('date', date('Y-m-d'))->value('price');
        if (empty($price)) {
            $this->result([], 1, '平台未设置价格');
        }
        $money = round($order['price'] / $price, 2);
        Db::startTrans();
        try {
            (new ContractSell())->where(['id' => $order['id']])->update(['status' => 5]);
            if ($money > 0) {
                (new Users())->MoneyEdit($this->request->user_id, $this->request->user['money'], $money, 1, 8, '合约兑换', $order['id'], 0, 0, 0);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '兑换失败，请重试');
        }
        $this->result([], 0, '兑换成功');
    }

    public function haveExchange()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require|in:1,2'
            ], [
                'type.require' => '兑换类型不能为空',
                'type.in' => '兑换类型不正确'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //获取收益中合约总值
            $config = (new Config())->where('key', 'contractsfee')->value('value');
            $config = json_decode($config, true);
            $user = $this->request->user;
            if ($user['allincome'] < $config['havemoney']) {
                $this->result([], 1, '推广收益累计不能低于' . $config['havemoney'] . '元');
            }
            $allorder = (new ContractOrder())->where(['user_id' => $this->request->user_id, 'income_status' => 2, 'status' => 3])->sum('price');
            if ($allorder < $config['money']) {
                $this->result([], 1, '收益中合约资产价值不能低于' . $config['money'] . '元');
            }
            if ($data['type'] == 1 && empty($data['id'])) {
                $this->result([], 1, '请选择需要兑换的合约');
            }
            if ($data['type'] == 2 && empty($data['money'])) {
                $this->result([], 1, '请选择需要兑换的金额');
            }
            if ($data['type'] == 1) {
                $cons = (new ContractList())->where(['id' => $data['id'], 'status' => 1])->find();
                if (empty($cons)) {
                    $this->result([], 1, '该合约已关闭');
                }
                //判断数量是否足够
                $handfee = round($cons['min_price'] * $config['handfee'] / 100, 2);
                if ($user['assets'] < ($handfee + $cons['min_price'])) {
                    $this->result([], 1, '资产不足，本次手续费:' . $handfee);
                }
                Db::startTrans();
                try {
                    (new ContractApply())->insert([
                        'user_id' => $user['id'],
                        'type' => $data['type'],
                        'contractid' => $data['id'],
                        'money' => $cons['min_price'],
                        'hand_fee' => $handfee,
                        'status' => 1
                    ]);
                    if (($handfee + $cons['min_price']) > 0) {
                        (new Users())->MoneyEdit($this->request->user_id, $this->request->user['assets'], - ($handfee + $cons['min_price']), 4, 4, '兑换合约');
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    $this->result([], 1, '兑换失败，请重试');
                }
                $this->result([], 0, '兑换成功，等待审核');
            }

            if ($data['type'] == 2) {
                //判断数量是否足够
                if (empty($data['money'])) {
                    $this->result([], 1, '兑换数量不能为空');
                }
                $price = (new CoinsPrice())->where('date', date('Y-m-d'))->value('price');
                if (empty($price)) {
                    $this->result([], 1, '平台未设置价格');
                }
                $money = round($data['money'] * $price, 2);
                $handfee = round($money * $config['handfee'] / 100, 2);
                if ($user['assets'] < ($handfee + $money)) {
                    $this->result([], 1, '资产不足，本次共需要:' . ($money + $handfee));
                }
                Db::startTrans();
                try {
                    (new ContractApply())->insert([
                        'user_id' => $user['id'],
                        'type' => $data['type'],
                        'money' => $data['money'],
                        'price' => $price,
                        'hand_fee' => $handfee,
                        'status' => 2
                    ]);
                    if (($handfee + $data['money']) > 0) {
                        (new Users())->MoneyEdit($this->request->user_id, $this->request->user['assets'], - ($handfee + $money), 4, 5, '兑换PDB');
                    }
                    (new Users())->MoneyEdit($this->request->user_id, $this->request->user['money'], $data['money'], 1, 9, '推广收益兑换');
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    $this->result([], 1, '兑换失败，请重试');
                }
                $this->result([], 0, '兑换成功');
            }
        } else {
            $config = (new Config())->where('key', 'contractsfee')->value('value');
            $config = json_decode($config, true);
            $this->result($config, 0, '兑换成功');
        }
    }
}
